package com.onepice.mlp.api.controller;

import com.alibaba.fastjson.JSONObject;
import com.onepice.mlp.api.common.CommonForUser;
import com.onepice.mlp.api.config.UserProfile;
import com.onepice.mlp.core.service.GroupdService;
import com.onepice.mlp.core.service.SyslogService;
import com.onepice.mlp.core.service.UserService;
import com.onepice.mlp.data.entity.Groupd;
import com.onepice.mlp.data.entity.Syslog;
import com.onepice.mlp.data.entity.User;
import com.onepice.mlp.utils.commom.ConvUtil;
import com.onepice.mlp.utils.commom.EncodeUtil;
import com.onepice.mlp.utils.commom.PageUtil;
import com.onepice.mlp.utils.commom.ResponseResult;
import com.onepice.mlp.utils.enums.CodeType;
import com.onepice.mlp.utils.enums.SyslogType;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


/**
 * @author FireWang
 * @date 2022/07/11 18:26:57
 */
@Slf4j
@AllArgsConstructor
@Controller
@RequestMapping("/user")
public class UserController {
    private UserService userService;
    private SyslogService syslogService;
    private GroupdService groupdService;
    private static JSONObject result;

    /**
     * 初始化用户管理
     *
     * @param model
     * @param username
     * @param phone
     * @param status
     * @param page
     * @param pageSize
     * @param maxPage
     * @param columns
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/list")
    public String listinit(HttpServletRequest request, Model model, String username, String phone, Integer status,
                           Integer page, Integer pageSize, Integer maxPage, Integer columns) throws Exception {
        try {
            //当前用户信息
            model = CommonForUser.getUserinfo(model, request);

            // 创建翻页工具，并添加查询条件
            PageUtil currentPage = new PageUtil(page, pageSize);
            currentPage.getParamMap().put("userName", username);
            currentPage.getParamMap().put("phone", phone);
            currentPage.getParamMap().put("status", status);

            // 获取设备信息列表
            Page<User> dataPage = userService.getUserForPage(currentPage);

            //初始化页面
            currentPage.setColumns(ConvUtil.convToInt(dataPage.getTotalElements()));
            model = CommonForUser.initPage(model, currentPage);

            //还原查询条件
            model.addAttribute("username", username);
            model.addAttribute("phone", phone);
            model.addAttribute("status", status);

            //数据列表
            model.addAttribute("dataPage", dataPage);

        } catch (Exception e) {
            log.error(e.getMessage());
            e.printStackTrace();
        }
        return "thymeleaf/user";
    }

    /**
     * 根据id获取
     *
     * @param id
     * @return
     */
    @GetMapping
    public JSONObject getById(@RequestParam Integer id) {
        try {
            User user = userService.getById(id);
            result = ResponseResult.build(CodeType.SUCCESS, "成功！");
            result.put("data", user);
        } catch (Exception e) {
            log.error(e.getMessage());
            result = ResponseResult.build(CodeType.FAIL, "失败：" + e.getMessage());
        }
        return result;
    }

    /**
     * 添加用户
     *
     * @param id
     * @param username
     * @param phone
     * @param newPwd
     * @param newPwdConfirm
     * @param realname
     * @param userpermission
     * @return
     */
    @PostMapping
    @ResponseBody
    public JSONObject adduser(HttpServletRequest request, int id, String username, String phone,
                              String newPwd, String newPwdConfirm, String realname, String userpermission) {
        try {
            String remark = "";
            String[] groupIds = userpermission.split(",");
            for (int i = 0; i < groupIds.length; i++) {
                Groupd group = groupdService.getById(ConvUtil.convToInt(groupIds[i]));
                if (i == 0) {
                    remark = group.getName();
                } else {
                    remark += "," + group.getName();
                }
            }

            if (id != 0) {
                //id不为0则为设置权限
                User user = userService.getById(id);
                user.setGroupId(userpermission);
                user.setRemark(remark);
                userService.update(user);
            } else {
                //当前用户信息
                UserProfile userProfile = CommonForUser.getUserProfile(request);

                //检查用户必填
                if ("".equals(username) || "".equals(phone) || "".equals(newPwd)) {
                    result = ResponseResult.build(CodeType.FAIL, "保存失败：请填写完整带“*”号的信息！");
                    return result;
                }

                //检查用户是否存在，若不存在则可插入
                if (userService.getUserByUerName(username.trim()) != null) {
                    result = ResponseResult.build(CodeType.FAIL, "保存失败：用户名已存在！");
                    return result;
                }
                if (userService.getUserByPhone(phone.trim()) != null) {
                    result = ResponseResult.build(CodeType.FAIL, "保存失败：手机号已存在！");
                    return result;
                }
                if (!newPwd.equals(newPwdConfirm)) {
                    result = ResponseResult.build(CodeType.FAIL, "保存失败：登录密码与确认密码不一致！");
                    return result;
                }
                User user = User.builder()
                        .userType(2)
                        .userName(username.trim())
                        .phone(phone.trim())
                        .password(EncodeUtil.getPasswordMd5(newPwd))
                        .realName(realname)
                        .groupId(userpermission)
                        .status(1)
                        .remark(remark)
                        .build();
                userService.insert(user);

                //添加系统日志
                Syslog syslog = Syslog.builder()
                        .type(SyslogType.ADD_USER.getValue())
                        .options(SyslogType.ADD_USER.getName())
                        .logInfo("用户(" + userProfile.getCurrentUserLoginName() + ")" + SyslogType.ADD_USER.getName())
                        .userId(userProfile.getCurrentUserId())
                        .userIp(userProfile.getCurrentUserLoginIp())
                        .build();
                syslogService.insert(syslog);
            }
            result = ResponseResult.build(CodeType.SUCCESS, "成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result = ResponseResult.build(CodeType.FAIL, "保存失败：系统异常！");
        }
        return result;
    }

    /**
     * 编辑用户
     *
     * @param id
     * @param pwdReset
     * @param status
     * @param delflag
     * @return
     */
    @PutMapping
    @ResponseBody
    public JSONObject edituser(HttpServletRequest request, Integer id, String pwdReset, String status, String delflag) {
        try {
            //当前用户信息
            UserProfile userProfile = CommonForUser.getUserProfile(request);
            if (userProfile.isTheAdmin()) {
                User user = userService.getById(id);
                //检查用户是否存在
                if (user != null) {
                    if (!"".equals(ConvUtil.convToString(pwdReset))) {
                        user.setPassword(EncodeUtil.getPasswordMd5("111111"));
                        userService.update(user);

                        //添加系统日志
                        Syslog syslog = Syslog.builder()
                                .type(SyslogType.RESET_PW.getValue())
                                .options(SyslogType.RESET_PW.getName())
                                .logInfo("用户(" + userProfile.getCurrentUserLoginName() + ")重置用户(" + user.getUserName() + ")密码：111111")
                                .userId(userProfile.getCurrentUserId())
                                .userIp(userProfile.getCurrentUserLoginIp())
                                .build();
                        syslogService.insert(syslog);
                    }
                    if (!"".equals(ConvUtil.convToString(status))) {
                        user.setStatus(ConvUtil.convToInt(status));
                        userService.update(user);
                    }
                    if (!"".equals(ConvUtil.convToString(delflag))) {
                        userService.deleteById(id);

                        //添加系统日志
                        Syslog syslog = Syslog.builder()
                                .type(SyslogType.DELETE_USER.getValue())
                                .options(SyslogType.DELETE_USER.getName())
                                .logInfo("用户(" + userProfile.getCurrentUserLoginName() + ")删除用户：" + user.getUserName())
                                .userId(userProfile.getCurrentUserId())
                                .userIp(userProfile.getCurrentUserLoginIp())
                                .build();
                        syslogService.insert(syslog);
                    }

                } else {
                    result = ResponseResult.build(CodeType.FAIL, "操作失败：未找到用户！");
                }
            } else {
                result = ResponseResult.build(CodeType.FAIL, "非管理员账号：没有操作权限！");
            }
            result = ResponseResult.build(CodeType.SUCCESS, "成功！");
        } catch (Exception e) {
            e.printStackTrace();
            result = ResponseResult.build(CodeType.FAIL, "操作失败：系统异常！");
        }
        return result;
    }
}

